package com.example.he.p0309_focusevent;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class FocusEventActivity extends AppCompatActivity {
    //定义4个EditText
    FocusEditText focusEditText1;
    FocusEditText focusEditText2;
    FocusEditText focusEditText3;
    FocusEditText focusEditText4;

    // 声明myEditText04的引用
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建4个FocusEditText对象
        focusEditText1 = new FocusEditText(this);
        focusEditText2 = new FocusEditText(this);
        focusEditText3 = new FocusEditText(this);
        focusEditText4 = new FocusEditText(this);
        //设置focusEditText1上的文字
        focusEditText1.setText("focusEditText1");
        // 设置focusEditText2上的文字
        focusEditText2.setText("focusEditText2");
        // 设置focusEditText3上的文字
        focusEditText3.setText("focusEditText3");
        // 设置focusEditText4上的文字
        focusEditText4.setText("focusEditText4");
        // 创建一个线性布局
        LinearLayout linearLayout = new LinearLayout(this);
        // 设置其布局方式为垂直
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        // 将focusEditText1添加到布局中
        linearLayout.addView(focusEditText1);
        // 将focusEditText2添加到布局中
        linearLayout.addView(focusEditText2);
        // 将focusEditText3添加到布局中
        linearLayout.addView(focusEditText3);
        // 将focusEditText4添加到布局中
        linearLayout.addView(focusEditText4);
        // 设置当前的用户界面
        setContentView(linearLayout);

    }

    class FocusEditText extends EditText {
        // 自定义EditText
        public FocusEditText(Context context) {
            // 构造器
            super(context);
        }

        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            String suffix = "- choose";
            String text = getText().toString();
            // 重写的焦点变化方法
            Toast.makeText(getContext(), "焦点改变", Toast.LENGTH_SHORT).show();
            if(focused){
                //获取焦点时，添加(选中)文字
                if(!text.contains(suffix)){
                    this.setText(text+suffix);
					Log.d("点击事件","true");
					Toast.makeText(getContext(), "获取焦点", Toast.LENGTH_SHORT).show();
                }
            }else{
                //去掉(选中)文字
                if(text.contains(suffix)){
                    text = text.substring(0,text.length()-suffix.length());
                    this.setText(text);
                }
            }
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }
    }
}
